<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>postBarContent</title>

    <script type="text/javascript" src="../js/jquery.js"></script>
    <script type="text/javascript" src="../bootstrap/js/bootstrap.js"></script>
    <script type="text/javascript" src="../js/message.js"></script>
    <script type="text/javascript" src="../js/myUtil.js"></script>

    <link rel="stylesheet" type="text/css" href="../bootstrap/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="../bootstrap/css/bootstrap-theme.css">
    <link rel="stylesheet" type="text/css" href="../css/page.css">
    <link rel="stylesheet" type="text/css" href="../css/message.css">


</head>
<body>
    <div class="container">
        <br>
        <div class="row" >
            <input class="col-md-7  col-md-offset-2" type="text" id="searchInput" style="font-size: 18px; padding: 7px">
            <button class="col-md-1" style="font-size: 18px; padding: 7px; margin-left: 5px" onclick="searchPost()">吧内搜索</button>
            <a class="col-md-1" style="font-size: 15px" href="createPost.html">发布贴子</a>
        </div>
        <br>

        <div class="row ">

            <div class="col-md-4">
                <!--显示当前用户信息-->
                <div class="col-md-12" style="border: 1px solid black">
                    <div class="col-md-12" style="height: 20px"></div>
                    <div class="col-md-2"><img class="img-circle" src="head.jpeg" style="width: 50px; height: 50px" id="userHead" alt="头像"></div>
                    <div class="col-md-10">
                        <a class="col-md-12" style="font-size: 20px; font-weight: bold ;font-family: 微软雅黑,serif; overflow: hidden;white-space: nowrap;text-overflow:ellipsis;" id="user" target="_blank" href="userData.html">用户昵称</a>
                        <label class="col-md-12" style="font-size: 15px" id="role">普通用户</label>
                    </div>
                    <div class="col-md-12" style="height: 10px"></div>
                </div>

                <div class="col-md-12" style="height: 20px"></div>

                <!--显示吧主与贴吧信息-->
                <div class="col-md-12" style="border: 1px solid black">

                    <!--吧主信息-->
                    <div class="col-md-12" style="height: 20px"></div>
                    <div class="col-md-2"><img class="img-circle" src="head.jpeg" style="width: 50px; height: 50px;  border: 1px solid black" id="creatorHead" alt="头像"></div>
                    <div class="col-md-10">
                        <label class="col-md-12" style="font-size: 20px; font-weight: bold ;font-family: 微软雅黑,serif; overflow: hidden;white-space: nowrap;text-overflow:ellipsis;; cursor:pointer; color: #0000cc" id="creator" onclick="toUserHome()">用户昵称</label>
                        <label class="col-md-12" style="font-size: 15px" id="creatorRole">普通用户</label>
                    </div>
                    <div class="col-md-12" style="height: 10px"></div>

                    <!--贴吧信息-->
                    <div class="col-md-12" style="border-bottom: 1px solid gray"></div>
                    <div class="col-md-12" style="height: 10px"></div>
                    <!--贴吧名字-->
                    <label class="col-md-9" style="font-size: 18px; font-weight: bold ;font-family: 微软雅黑,serif;" id="postBarName">贴吧名</label>
                    <!--关注贴吧按钮-->
                    <label class="col-md-3" style="font-size: 15px; color: #0000cc; cursor: pointer; text-align: right" id="followPostBar" onclick="changePostBarFollow()">关注</label>
                    <label class="col-md-12" style="font-size: 18px; font-weight: bold ;font-family: 微软雅黑,serif;" id="postBarFollow">关注数</label>
                    <label class="col-md-12" style="font-size: 18px; font-weight: bold ;font-family: 微软雅黑,serif;" id="postNumbers">贴子数</label>
                    <div class="col-md-12" style="height: 10px"></div>
                    <div class="col-md-12" style="border-bottom: 1px solid gray"></div>
                    <div class="col-md-12" style="height: 10px"></div>
                    <p class="col-md-12" style="font-size: 18px; font-weight: bold ;font-family: 微软雅黑,serif; text-align: justify; white-space: pre-wrap" id="postBarResume">简介：</p>
                    <div class="col-md-12" style="height: 10px"></div>

                </div>
                <div class="col-md-12" style="height: 20px"></div>

                <!--显示吧主权限-->
                <div class="col-md-12" style="border: 1px solid black; display: none" id="creatorBar">
                    <br>
                    <label class="col-md-12" style="font-size: 20px; text-align: center; color: mediumorchid">吧主权限</label>
                    <div class="col-md-12" style="height: 10px"></div>

                    <div class="col-md-12" style="border-top: 1px solid gray; padding-top: 15px; padding-bottom: 15px" onmouseover=over(this) onmouseout=out(this)>
                        <a class="col-md-12" href="postRecycle.html"><label style="font-size: 20px; cursor: pointer; color: #333333" id="postRecycle">贴子回收站</label></a>
                    </div>
                </div>
            </div>

            <!--显示贴子列表-->
            <div class="col-md-8">
                <!--显示贴子数量-->
                <div class="col-md-10"><label class="row" style="font-size: 16px; color: #666666; display: none" id="postNumberTip"></label></div>
                <!--显示贴吧排序方式-->
                <div class="col-md-2 row-no-gutters">
                    <button class="col-md-6" style="border: 0; background: #00000000; font-size: 14px; color: #FF0000; text-align: right; cursor: pointer" onselect="return false" sortWay="desc" select="1" id="timeSort" onclick="changeSort(1)">时间 ↑</button>
                    <button class="col-md-6" style="border: 0; background: #00000000;font-size: 14px; color: #666666; text-align: right; cursor: pointer" onselect="return false" sortWay="desc" select="0" id="commentSort" onclick="changeSort(2)">回复 ↑</button>
                </div>


                <!--显示公告贴-->
                <div class="col-md-12" id="postNoticeList"></div>
                <!--显示普通贴子-->
                <div class="col-md-12" id="postList"></div>

                <div class="col-md-12" style="height: 20px"></div>
                <!--显示翻页器-->
                <div class="row" nowPage="1" maxPage="1" maxDisplay="8" id="pageTurner">
                    <button class="col-md-2 col-md-offset-2" style="border: 1px solid black; height: 40px; text-align: center"  onmouseover=over(this) onmouseout=out(this) onclick="updatePageTurnerRoot(-1, totalNum, getPagePost)">上一页</button>
                    <label class="col-md-2 col-md-offset-1" style="font-size: 20px; text-align: center" id="pageLabel">1 / 1</label>
                    <button class="col-md-2 col-md-offset-1" style="border: 1px solid black; height: 40px; text-align: center;"  onmouseover=over(this) onmouseout=out(this) onclick="updatePageTurnerRoot(1, totalNum, getPagePost)">下一页</button>
                </div>
            </div>

            <div class="col-md-12" style="height: 40px"></div>

        </div>
    </div>



    <script type="text/javascript">
        let postNoticeList = $("#postNoticeList");
        let postList = $("#postList");

        let user, postBar, posts;
        var totalNum;

        // 保存搜索字段
        let searchContent;
        // 保存
        let postNumberTip = $("#postNumberTip");

        // 排序方式
        let sortClass = "create_date", sortWay = "desc";
        let timeSort = $("#timeSort");
        let commentSort = $("#commentSort");

        // 请求得到用户信息
        $.ajaxSettings.async = false;
        $.post("/QG_PostBar/user?method=getUserBySession", function (data){
            user = data;
            $("#user").html(user.userName + "（我）");
            if (user.userHead != null) {
                $("#userHead").attr("src", "/QG_PostBar/user_head/" + user.userHead);
            }

            // 检查用户是否已经关注该贴吧
            $.get("/QG_PostBar/postBar?method=isUserFollowPostBar", function (data) {
                if (data === "true") {
                    $("#followPostBar").css("color", "red").html("已关注");
                }
            });

            // 判断身份
            if(user.userRole === 1) {
                $("#role").html("系统管理员");
            }

        }, "json");

        // 请求得到贴吧信息
        $.post("/QG_PostBar/postBar?method=getPostBarBySession", function (data){
            // 获得贴吧json
            postBar = data;

            // 修改绑定
            nowPostBar = postBar;

            // 请求得到吧主信息
            $.get("/QG_PostBar/user?method=getUserById", {"userId": postBar.userId}, function (data){
                $("#creator").html(data.userName + "（吧主）");
                if (data.userHead != null) {
                    $("#creatorHead").attr("src", "/QG_PostBar/user_head/" + data.userHead);
                }

                // 判断身份
                if(data.userRole === 1) {
                    $("#creatorRole").html("系统管理员");
                }
                // 是贴吧吧主的话显示吧主权限
                if(user.userId === data.userId) {
                    $("#creatorBar").show();
                }
            }, "json");

            // 写上贴吧名、关注数、贴子数和简介
            $("#postBarName").html("贴吧名：" + postBar.postBarName);
            $("#postBarFollow").html("关注数：" + postBar.postBarFollow);
            $("#postNumbers").html("贴子数：" + postBar.postNumber);
            $("#postBarResume").html("简介：\n" + postBar.postBarResume);

            $("#postNumberTip").html("共有 " + postBar.postNumber + " 个贴子");
            // 更新翻页器
            totalNum = postBar.postNumber;
            updatePageTurnerRoot(0, totalNum);

            // 先自己来一次
            getPagePost();

        }, "json");
        $.ajaxSettings.async = true;

        // 模糊搜索贴子
        function searchPost() {
            // 获取搜索框内容
            searchContent = $("#searchInput").val();

            // 获取有多少的搜索结果
            $.get("/QG_PostBar/post?method=getAllSearchForNumber", {"postBarId": postBar.postBarId, "search": searchContent} ,function (data){
               totalNum = parseInt(data);
               updatePageTurnerRoot(0, totalNum);

               if (searchContent !== undefined && searchContent !== "") {
                    postNumberTip.show();
                    postNumberTip.html("共搜索到 " + totalNum + " 个贴子");
               } else {
                    postNumberTip.hide();
               }
            });

            getPagePost();
        }

        // 请求得到贴子，有搜索的加入搜索条件
        function getPagePost() {
            // 获取翻页器
            let pageTurner = $("#pageTurner");

            // 获取当前页数和最大显示数量
            // 获取到翻页器的当前页数和最大显示数量
            let nowPage = parseInt(pageTurner.attr("nowPage"));
            let maxDisplay = parseInt(pageTurner.attr("maxDisplay"));

            $.post("/QG_PostBar/post?method=getAllPostByPage",
                {"postBarId": postBar.postBarId, "search": searchContent, "page": nowPage, "num": maxDisplay, "postDelete": 0, "sortClass": sortClass, "sortWay": sortWay}, function (data){
                // 先清空列表
                postNoticeList.empty();
                postList.empty();

                // 将数据取出来并显示（将这一部分设置为同步请求，保证各个贴子的顺序）
                $.ajaxSettings.async = false;
                for (const key in data) {
                    // 获取贴子对象
                    const post = data[key];
                    // 获取贴子的创建者后，将标签添加进来
                    $.get("/QG_PostBar/user?method=getUserById", {"userId": post.userId}, function (user){
                        // 获取标题
                        let title = post.postName;
                        let detail = post.postContent;
                        // 如果有搜索字段的话，将搜索字段的关键字变红
                        if (searchContent !== undefined) {
                            title = title.replace(eval("/"+ searchContent +"/g"),"<span style='color:red;'>"+ searchContent +"</span>");
                            detail = detail.replace(eval("/"+ searchContent +"/g"),"<span style='color:red;'>"+ searchContent +"</span>");
                        }

                        // 有的话放在公告栏处
                        if (post.postAdminId !== null) {
                            addNotice(postNoticeList, "/QG_PostBar/post?method=getPostById&postId=" +post.postId + "&isClick=true", title, post.createDate);
                        } else {
                            addItem(postList, "/QG_PostBar/post?method=getPostById&postId=" +post.postId + "&isClick=true",
                                title, "简介：" + detail, user.userName, post.createDate);
                        }

                    }, "json");
                }
                $.ajaxSettings.async = true;
            }, "json");
        }

        /**
         * 改变排序方式
         * 如果当前排序方式没有选中，那么选中它
         * 如果已选中，那么更改升降序
         */
        function changeSort(which) {

            if (which === 1) {
                sortClass = "create_date";
                // 如果已经选中，那么倒换升降序
                if (timeSort.attr("select") === "1") {
                    if (timeSort.attr("sortWay") === "desc"){
                        timeSort.attr("sortWay", "asc");
                    } else {
                        timeSort.attr("sortWay", "desc");
                    }
                }
                sortWay = timeSort.attr("sortWay");
                timeSort.css("color", "#FF0000");
                timeSort.html("时间 " + (sortWay === "desc"? "↑" : "↓"));
                commentSort.css("color", "#666666");
                timeSort.attr("select", "1");
                commentSort.attr("select", "0");
            } else {
                sortClass = "post_comment";
                // 如果已经选中，那么倒换升降序
                if (commentSort.attr("select") === "1") {
                    if (commentSort.attr("sortWay") === "desc"){
                        commentSort.attr("sortWay", "asc");
                    } else {
                        commentSort.attr("sortWay", "desc");
                    }
                }
                sortWay = commentSort.attr("sortWay");
                commentSort.css("color", "#FF0000");
                commentSort.html("回复 " + (sortWay === "desc"? "↑" : "↓"));
                timeSort.css("color", "#666666");
                commentSort.attr("select", "1");
                timeSort.attr("select", "0");
            }

            getPagePost();
        }

        function toUserHome() {
            window.open("userHome.html?userId="+postBar.userId);
        }

        /**
         * 负责更新翻页器数据（作用的对象是静态添加的翻页器，而不是动态添加的列表中的翻页器）
         * 获取到翻页器和显示标签、以及要显示的总量
         * 更新最大页数
         * 然后通过翻页标识、当前页数和最大页数判断如何执行翻页操作
         * @param turnPage 翻页标识（-1表示上一页，0表示不翻页，1表示下一页）
         * @param totalNum 目前翻页器对应列表的数据总条数
         * @param updatePage 作为回调函数，即发生翻页后调用来显示新的数据
         */
        function updatePageTurnerRoot(turnPage, totalNum, updatePage) {
            // 获取翻页器和显示标签
            let pageTurner = $("#pageTurner");
            let pageLabel = $("#pageLabel");

            // 获取到翻页器的当前页数和最大显示数量
            let nowPage = parseInt(pageTurner.attr("nowPage"));
            let maxDisplay = parseInt(pageTurner.attr("maxDisplay"));

            // 计算最大页数
            let newMaxPage;
            if (totalNum === 0) {
                newMaxPage = 1
            } else {
                newMaxPage =  Math.floor((totalNum-1) / maxDisplay) + 1;
            }

            // 判断翻页标识
            let isTurn = false;
            if (nowPage+turnPage > 0 && nowPage+turnPage <= newMaxPage) {
                nowPage += turnPage;
                isTurn = true;
            }

            // 判断更新后的页数变化（可能执行了删除操作，导致当前页数小于最大页数，这时候要将当前页数改为最大页数）
            if (nowPage > newMaxPage) {
                nowPage = newMaxPage;
            }

            // 将新的数据显示出来
            pageLabel.html(nowPage + " / " + newMaxPage);

            // 将新的数据更新到翻页器中
            pageTurner.attr("nowPage", "" + nowPage);
            pageTurner.attr("maxPage", "" + newMaxPage);
            pageTurner.attr("maxDisplay", "" + maxDisplay);

            // 调用翻页函数
            if (updatePage !== undefined && isTurn) {
                updatePage(searchContent);
            }
        }

        // 改变贴吧关注
        function changePostBarFollow() {
            $.get("/QG_PostBar/postBar?method=changePostBarFollow", function (data){
                // 判断是关注还是取消关注，改变对应的显示，然后更新贴吧数据
                if (data === "create") {
                    postBar.postBarFollow++;
                    $("#followPostBar").css("color", "red").html("已关注");
                } else{
                    postBar.postBarFollow--;
                    $("#followPostBar").css("color", "#0000cc").html("关注");
                }
                $("#postBarFollow").html("关注数：" + postBar.postBarFollow);
            }, "text");
        }
    </script>
</body>
</html>